package logic

import (
	"context"
	"encoding/json"
	"homes/models/cache"
	"homes/models/mysql"
	"time"

	"homes/homerpc/homerpc"
	"homes/homerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type HouseListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHouseListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HouseListLogic {
	return &HouseListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HouseListLogic) HouseList(in *homerpc.HouseListRequest) (*homerpc.HouseListResponse, error) {
	// todo: add your logic here and delete this line
	var house []mysql.House

	result, _ := cache.Rdb.Get(l.ctx, "houseList").Result()
	if result == "" {
		mysql.DB.Debug().Find(&house)
		marshal, _ := json.Marshal(house)
		cache.Rdb.Set(l.ctx, "houseList", marshal, time.Minute*3)
	} else {
		json.Unmarshal([]byte(result), &house)
	}
	var houseList []*homerpc.HouseList
	for _, m := range house {
		list := homerpc.HouseList{
			Id:        int64(m.ID),
			Address:   m.Address,
			HouseName: m.HouseName,
			Price:     float32(m.Price),
			Status:    m.Status,
		}
		houseList = append(houseList, &list)
	}
	return &homerpc.HouseListResponse{
		List: houseList,
	}, nil
}
